package service

import (
	"errors"

	"github.com/google/uuid"

	"go_user_manager/internal/adapters/controllers/view_model"
	"go_user_manager/internal/domain"
	"go_user_manager/internal/domain/repo"
	"go_user_manager/pkg/framework"
)

type UserService struct {
	logger   framework.Logger
	userRepo repo.IUserRepo
}

func NewUserService(logger framework.Logger, userRepo repo.IUserRepo) *UserService {
	return &UserService{
		logger:   logger,
		userRepo: userRepo,
	}
}

func (s *UserService) Add(userNew view_model.CreateUserReq) error {
	user := domain.User{
		ID:       uuid.NewString(),
		UserName: userNew.UserName,
		Password: userNew.Password,
		Email:    userNew.Email,
	}

	return s.userRepo.Add(user)
}

func (s *UserService) Get(id, userName string) (*domain.User, error) {
	return s.userRepo.Get(id, userName)
}

func (s *UserService) Update(userUpdate view_model.UpdateUserReq) error {
	_, err := s.userRepo.Get(userUpdate.ID, "")
	if err != nil {
		return err
	}

	userDomain := domain.User{
		ID:       userUpdate.ID,
		UserName: userUpdate.UserName,
		Password: userUpdate.Password,
		Email:    userUpdate.Email,
	}
	return s.userRepo.Update(userDomain)
}

func (s *UserService) Delete(id string) error {
	return s.userRepo.Delete(id)
}

func (s *UserService) List(userListQuery domain.UserListQuery) ([]domain.User, int64, error) {
	return s.userRepo.List(userListQuery)
}

func (s *UserService) VerifyUser(userName string, userPassword string) (*domain.User, error) {
	// 根据用户名查找用户
	users, total, err := s.userRepo.List(domain.UserListQuery{UserName: userName})
	if err != nil {
		return nil, err
	}
	if total == 0 {
		return nil, errors.New("invalid username or password")
	}

	user := users[0]
	// 验证密码
	if user.Password != userPassword {
		return nil, errors.New("invalid username or password")
	}

	// 返回用户信息和token
	return &user, nil
}
